﻿using System;
using System.Collections.Generic;
using System.Text;
using NLBS.Framework;
using System.Globalization;
using NLBS.Entity;

namespace NLBS.Data.Business
{
    public class WidgetData 
    {
        private static readonly string widgetKey = "widgetKey";

        public static List<Widget> GetWidget()
        {
            
            ContentCache cache = ContentCache.Instantiate();
            List<Widget> lists = (List<Widget>)cache[widgetKey];
            if (lists == null)
            {
                lists = new List<Widget>(DbProvider.Instance().GetWidget());
                if (lists != null)
                {
                    cache.Insert(widgetKey, lists, CacheDuration.Long);
                }
            }
            return lists;
        }

        public static List<Widget> WidgetList
        {
            get
            {
                return GetWidget();
            }
        }
        public static List<Widget> GetWidgetList()
        {
            WidgetList.Sort(Compare);
            return WidgetList;
        }

        public static Widget GetWidgetByID(int id)
        {
            return WidgetList.Find(delegate(Widget c)
            {
                return c.WidgetID == id;
            });

        }

        public static void InsertWidget(Widget cat)
        {
            int result = DbProvider.Instance().InsertWidget(cat);
            cat.WidgetID = result;
            WidgetList.Add(cat);
        }

        public static int Compare(Widget x, Widget y)
        {
            if (x == null)
            {
                if (y == null)
                {

                    return 0;
                }
                else
                {

                    return -1;
                }
            }
            else
            {

                if (y == null)
                {
                    return 1;
                }
                else
                {

                    int retval = x.Order.CompareTo(y.Order);

                    if (retval != 0)
                    {
                        return retval;
                    }
                    else
                    {
                        return x.Order.CompareTo(y.Order);
                    }
                }
            }
        }

        public static void UpdateWidget(Widget cat)
        {
            DbProvider.Instance().UpdateWidget(cat);
           
        }

        public static void DeleteWidget(int catID)
        {
            DbProvider.Instance().DeleteWidget(catID);

            WidgetList.Remove(GetWidgetByID(catID));
        }
    }
}
